import 'dart:async';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/pay_model/user_list_pay_certification_model.dart';
import 'package:yysk_app/model/pay_model/user_register_apply_model.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/enterprise_auth_zhifu/my_webview_zhifu_open_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/enterprise_auth_zhifu/my_webview_zhifu_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/open_wallet_fail/open_wallet_fail_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:lottie/lottie.dart';
import 'package:oktoast/oktoast.dart';

import '../../../../model/pay_model/user_pay_zhifu_url.dart';
import '../enterprise_auth_zhifu/my_webview_zhifu_user_page.dart';

class WalletController extends GetxController {
  // 这里可以添加钱包相关的状态和方法

  // final ScrollController scrollController = ScrollController();
  GlobalController globalController = Get.find();
  final listPayCertification = RxList<UserListPayCertificationModel?>([]);
  bool zhifuIsRefresh = false;
  Timer? _timer;
  String? plat;
  String? channel;
  final hasWallet = RxDouble(0);
  @override
  void onInit() {
    super.onInit();
    // 初始化逻辑
    globalController.getXPayToken().then((r) {
      getListPay();
      getPlatWallet();
    });
    zhifuIsRefresh = false;
  }

  void getPlatWallet() {
    http.netFetch<dynamic>(
      PayUrl.getPlatWalletBalance,
      success: (res) {
        hasWallet.value = res.data ?? 0.00;
      },
    );
  }

  Future<void> handleRefresh() async {
    globalController.getXPayToken().then((r) {
      getListPay();
      getPlatWallet();
    });
    return;
  }

  Future getListPay() async {
    await http.netFetch<List<UserListPayCertificationModel>>(
      PayUrl.listPayCertification,
      method: Method.post,
      params: {},
      success: (res) {
        listPayCertification.value = res.data ?? [];
      },
    );
  }

  Future getWalletUrl(String plat, String channel) async {
    await http.netFetch<UserPayZhifuUrlModel>(
      PayUrl.dinPayWallet,
      method: Method.post,
      params: {'plat': plat, 'channel': channel},
      success: (res) {
        if ((res.data?.walletUrl ?? '').isNotEmpty) {
          Get.toNamed(
            '${MyWebViewZhifuUserPage.path}?url=${Uri.encodeComponent(res.data?.walletUrl ?? '')}',
            arguments: {'url': Uri.encodeComponent(res.data?.walletUrl ?? '')},
          );
        } else {
          showToast('网络异常！');
        }
      },
    );
  }

  @override
  // ignore: unnecessary_overrides
  void onClose() {
    super.onClose();
    _timer?.cancel();
  }

  void startTime() {
    zhifuIsRefresh = false;

    
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      dinPayWalletIsSucceed();
    });
  }

  //查询智付是否开通成功
  int count = 0;
  Future<void> dinPayWalletIsSucceed() async {
    count += 1;
    if (count <= 2) {
      await http.netFetch<bool>(
        PayUrl.dinPayWalletIsSucceed,
        method: Method.post,
        params: {'plat': plat, 'channel': channel},
        success: (result) {
          if (result.code == 200) {
            if (result.data == true) {
              //开通成功
              EasyLoading.dismiss();
              _timer?.cancel();
              handleRefresh();
            }
          }
        },
      );
    } else {
      EasyLoading.dismiss();
      count = 0;
      _timer?.cancel();
    }
  }

  Future<void> submit() async {
    http.netFetch<UserRegisterApplyModel>(
      PayUrl.registerApply,
      method: Method.post,
      params: {
        'channel': channel,
        'plat': "USER",
        'legalPersonInfo': {
          // 'certValidityType':isLong.value==true?1:0,
        },
      },
      success: (r) {
        if (r.data?.applicationStatus == 'REFUSE') {
          Get.toNamed(
            '${OpenWalletFailPage.path}?reason=${r.data?.reason}&channel=${channel}',
            arguments: {'reason': r.data?.reason, 'channel': channel},
          );
        } else if (r.data?.applicationStatus == 'PASS') {
          WalletController walletController = Get.find();
          walletController.getListPay().then((e) {
            Get.back();
          });
        } else if (r.data?.applicationStatus == 'WAITING' &&
            channel == 'DIN_PAY') {
          Get.toNamed(
            '${MyWebViewZhifuOpenPage.path}?url=${Uri.encodeComponent(r.data?.returnUrl ?? '')}',
            arguments: {'url': Uri.encodeComponent(r.data?.returnUrl ?? '')},
          );
        }
        return r;
      },
    );
    return;
  }
}
